#include <stdlib.h>
#include <string.h>
#include "student_manager.h"

// 内部扩容函数
static int manager_resize(StudentManager *manager) {
    if (!manager) return 0;

    int new_capacity = manager->capacity * 2;
    Student **new_students = (Student**)realloc(
        manager->students,
        new_capacity * sizeof(Student*)
    );

    if (!new_students) {
        fprintf(stderr, "错误：管理器扩容失败\n");
        return 0;
    }

    manager->students = new_students;
    manager->capacity = new_capacity;
    return 1;
}

// 创建管理器
StudentManager* manager_create(int initial_capacity) {
    if (initial_capacity <= 0) initial_capacity = 4;  // 最小容量

    StudentManager *manager = (StudentManager*)malloc(sizeof(StudentManager));
    if (!manager) {
        fprintf(stderr, "错误：管理器内存分配失败\n");
        return NULL;
    }

    manager->students = (Student**)malloc(initial_capacity * sizeof(Student*));
    if (!manager->students) {
        fprintf(stderr, "错误：学生数组内存分配失败\n");
        free(manager);
        return NULL;
    }

    manager->size = 0;
    manager->capacity = initial_capacity;
    return manager;
}

// 销毁管理器
void manager_destroy(StudentManager *manager) {
    if (manager) {
        // 销毁所有学生
        for (int i = 0; i < manager->size; i++) {
            student_destroy(manager->students[i]);
        }
        free(manager->students);  // 释放学生数组
        free(manager);            // 释放管理器
    }
}

// 添加学生
int manager_add_student(StudentManager *manager, Student *student) {
    if (!manager || !student) return 0;

    // 检查是否需要扩容
    if (manager->size >= manager->capacity) {
        if (!manager_resize(manager)) return 0;
    }

    manager->students[manager->size++] = student;
    return 1;
}

// 查找学生
Student* manager_find_student(const StudentManager *manager, int id) {
    if (!manager) return NULL;

    for (int i = 0; i < manager->size; i++) {
        if (student_get_id(manager->students[i]) == id) {
            return manager->students[i];
        }
    }
    return NULL;
}

// 删除学生
int manager_remove_student(StudentManager *manager, int id) {
    if (!manager) return 0;

    for (int i = 0; i < manager->size; i++) {
        if (student_get_id(manager->students[i]) == id) {
            // 销毁找到的学生
            student_destroy(manager->students[i]);
            
            // 移动数组元素填补空缺
            for (int j = i; j < manager->size - 1; j++) {
                manager->students[j] = manager->students[j + 1];
            }
            
            manager->size--;
            return 1;
        }
    }
    return 0;
}

// 更新学生信息
int manager_update_student(StudentManager *manager, int id, const char *new_name, float new_score) {
    Student *student = manager_find_student(manager, id);
    if (!student) return 0;

    if (new_name) {
        student_set_name(student, new_name);
    }
    student_set_score(student, new_score);
    return 1;
}

// 获取学生数量
int manager_get_count(const StudentManager *manager) {
    return manager ? manager->size : 0;
}

// 遍历所有学生
void manager_for_each(const StudentManager *manager, void (*callback)(const Student*)) {
    if (!manager || !callback) return;

    for (int i = 0; i < manager->size; i++) {
        callback(manager->students[i]);
    }
}

// 新增：导出学生数据到文件
int manager_export_to_file(const StudentManager *manager, const char *filename) {
    if (!manager || !filename) return 0;

    // 打开文件（文本模式，支持中文）
    FILE *file = fopen(filename, "w");
    if (!file) {
        fprintf(stderr, "错误：无法打开文件 %s 进行写入\n", filename);
        return 0;
    }

    // 写入学生数据（格式：学号|姓名|分数）
    for (int i = 0; i < manager->size; i++) {
        const Student *student = manager->students[i];
        // 使用竖线分隔避免中文逗号问题
        fprintf(file, "%d|%s|%.1f\n",
                student_get_id(student),
                student_get_name(student),
                student_get_score(student));
    }

    fclose(file);
    return 1;
}

// 新增：从文件导入学生数据
int manager_import_from_file(StudentManager *manager, const char *filename) {
    if (!manager || !filename) return 0;

    // 打开文件
    FILE *file = fopen(filename, "r");
    if (!file) {
        fprintf(stderr, "错误：无法打开文件 %s 进行读取\n", filename);
        return 0;
    }

    char line[512];
    int line_num = 0;
    int imported = 0;

    // 逐行读取并解析
    while (fgets(line, sizeof(line), file)) {
        line_num++;
        // 去除换行符
        line[strcspn(line, "\n")] = '\0';

        // 解析格式：id|name|score
        int id;
        char name[100];
        float score;
        char *id_str = strtok(line, "|");
        char *name_str = strtok(NULL, "|");
        char *score_str = strtok(NULL, "|");

        // 检查格式是否正确
        if (!id_str || !name_str || !score_str) {
            fprintf(stderr, "警告：第 %d 行格式错误，跳过\n", line_num);
            continue;
        }

        // 转换数据类型
        if (sscanf(id_str, "%d", &id) != 1) {
            fprintf(stderr, "警告：第 %d 行学号格式错误，跳过\n", line_num);
            continue;
        }
        if (sscanf(score_str, "%f", &score) != 1) {
            fprintf(stderr, "警告：第 %d 行分数格式错误，跳过\n", line_num);
            continue;
        }

        // 检查学号是否已存在
        if (manager_find_student(manager, id)) {
            fprintf(stderr, "警告：第 %d 行学号 %d 已存在，跳过\n", line_num, id);
            continue;
        }

        // 创建学生并添加到管理器
        Student *student = student_create(name_str, id, score);
        if (student && manager_add_student(manager, student)) {
            imported++;
        } else {
            fprintf(stderr, "警告：第 %d 行导入失败\n", line_num);
            student_destroy(student); // 清理失败的学生对象
        }
    }

    fclose(file);
    return imported;
}